package me.zk.practice1.s;

/**
 * @author zhangkai
 * @date 2023/8/10 12:12
 */
public class LS79 {
    static int[][] direction = {{0,1},{0,-1},{1,0},{-1,0}};

    public static void main(String[] args) {
        char[][] c = new char[1][1];
        c[0][0] = 'a';
        System.out.println(exist(c,"a"));
    }
    public static boolean exist(char[][] board, String word) {

        //
        int l = board.length;
        int h = board[0].length;
        boolean flag = false;
        boolean[][] used = new boolean[l][h];
        for (int i = 0; i < l; i++) {
            for (int j = 0; j <h; j++) {
                flag = check(board,word,0,used,i,j);
                if (flag) {
                    return true;
                }
            }
        }

        return false;
    }

    public static boolean check(char[][] board,String word,int index,boolean[][] used,int i, int j) {

        if (word.charAt(index)!=board[i][j]) {
            return false;
        } else if (index == word.length()-1) {
            return true;
        }
        boolean result = false;
        used[i][j] = true;
        for (int[] dir : direction) {
            int ni = i+dir[0];
            int nj = j+dir[1];
            if (ni>=0&&nj>=0&&ni<board.length&&nj<board[0].length) {
                if (!used[ni][nj]) {
                    boolean flag = check(board,word,index+1,used,ni,nj);
                    if (flag) {
                        result = true;
                        break;
                    }

                }
            }

        }
        used[i][j]=false;
        return result;
    }
}
